<!--
 * @Author: your name
 * @Date: 2020-10-12 12:53:58
 * @LastEditTime: 2020-10-19 15:02:51
 * @LastEditors: Please set LastEditors
 * @Description: 图表组件
-->
<template>
  <div ref="myChartRef"
       class="echarts"></div>
</template>

<script>
import {
  onMounted, onBeforeUnmount, ref, getCurrentInstance
} from "vue"

const echarts = require("echarts")

export default {
  name: "tao-charts",
  props: {
    data: {
      type: Object,
      default: null
    }
  },
  setup(props, context) {
    const { proxy } = getCurrentInstance()
    let resizeHandler
    const myChartRef = ref(null) // 定义ref
    const chartDrawLine = () => {
      const myChart = echarts.init(myChartRef.value)
      // 通过防抖调用resize 事件
      resizeHandler = proxy.$utils.debounce(() => {
        if (myChart) {
          myChart.resize()
        }
      }, 200)

      setTimeout(() => {
        if (props.data !== null) myChart.setOption(props.data)
      }, 500)
      myChart.on("click", (params) => {
        context.emit(`chart-${params.type}`, params)
        setTimeout(() => {
          chartDrawLine()
        }, 100)
      })
    }
    onMounted(() => {
      chartDrawLine()
      // 当浏览器窗口变化添加resize 事件
      window.addEventListener("resize", resizeHandler)
    })
    // 当浏览器窗口变化完移除resize 事件
    onBeforeUnmount(() => {
      window.removeEventListener("resize", resizeHandler)
    })
    return {
      myChartRef
    }
  }
}
</script>
<style lang="scss" scoped>
.echarts {
  height: 100%;
  width: 100%;
  position: relative;
}
</style>
